﻿/*
* public_news.cs
*
* 功 能： N/A
* 类 名： public_news
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.IO;
using System.Web;
using XHD.Common;
using XHD.Controller;
using XHD.DBUtility;

namespace XHD.Server
{
    public class public_news
    {
        public static BLL.public_news news = new BLL.public_news();
        public static Model.public_news model = new Model.public_news();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public public_news()
        {
        }

        public public_news(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string save()
        {
            model.news_title = PageValidate.InputText(request["T_title"], 255);
            model.news_content = PageValidate.InputText(request["T_content"], int.MaxValue);
            model.CaseVideoUrl = PageValidate.InputText(request["T_url"], 255);
            model.BannerImgUrl = PageValidate.InputText(request["headurl"], 255);
            model.News_type = PageValidate.InputText(request["T_type_val"], 55);
            string nid = PageValidate.InputText(request["nid"], 50);
            if (PageValidate.checkID(nid))
            {
                DataSet ds = news.GetList($"id = '{nid}' ");
                if (ds.Tables[0].Rows.Count == 0)
                    return XhdResult.Error("参数不正确，更新失败！").ToString();

                DataRow dr = ds.Tables[0].Rows[0];

                model.id = nid;

                news.Update(model);

                string UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.news_title;
                string EventType = "新闻修改";
                string EventID = model.id;
                string Log_Content = null;

                if (dr["news_title"].ToString() != request["T_title"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "新闻标题", dr["news_title"], request["T_title"]);

                if (dr["news_content"].ToString() != request["T_content"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "新闻内容", "原内容被修改", "原内容被修改");

                if (!string.IsNullOrEmpty(Log_Content))
                    Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.create_time = DateTime.Now;
                model.create_id = emp_id;
                model.id = Guid.NewGuid().ToString();
                
                news.Add(model);
            }
            return XhdResult.Success().ToString();
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " create_time";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total, serchtxt = $" 1=1 ";

            if (!string.IsNullOrEmpty(request["sstart"]))
                serchtxt += " and create_time >= '" + PageValidate.InputText(request["sstart"], 50) + "'";

            if (!string.IsNullOrEmpty(request["sdend"]))
            {
                DateTime enddate = DateTime.Parse(request["sdend"]).AddHours(23).AddMinutes(59).AddSeconds(59);
                serchtxt += " and create_time  <= '" + enddate + "'";
            }

            if (!string.IsNullOrEmpty(request["stext"]))
            {
                if (request["stext"] != "输入关键词搜索")
                    serchtxt += " and news_title like N'%" + PageValidate.InputText(request["stext"], 500) + "%'";
            }

            DataSet ds = news.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            return (GetGridJSON.DataTableToJSON1(ds.Tables[0], Total));
        }

        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = news.GetList($"id = '{id}' ");
            string dt = DataToJson.DataToJSON(ds);

            return dt;
        }

        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return XhdResult.Error("参数错误！").ToString();

            bool canDel = false;
            if (uid != "admin")
            {
                var getauth = new GetAuthorityByUid();
                canDel = getauth.GetBtnAuthority(emp_id.ToString(), "5CE532AF-69BE-4FB0-B32F-52F17A6FFD80");
                if (!canDel)
                    return XhdResult.Error("权限不够！").ToString();
            }

            id = PageValidate.InputText(id, 50);
            DataSet ds = news.GetList($"id='{id}' ");

            if (ds.Tables[0].Rows.Count < 1)
                return XhdResult.Error("系统错误，无数据！").ToString();

            bool isdel = news.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误！").ToString();

            //日志
            string EventType = "新闻删除";
            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = ds.Tables[0].Rows[0]["news_title"].ToString();

            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();
        }

        public string newsremind()
        {
            DataSet ds = news.GetList(7, $" 1=1 ", " create_time desc");
            string dt = GetGridJSON.DataTableToJSON(ds.Tables[0]);
            return dt;
        }


        public object RichUpload()
        {
            HttpPostedFile uploadFile = request.Files[0];
            string filename = uploadFile.FileName;
            string sExt = filename.Substring(filename.LastIndexOf(".")).ToLower();
            DateTime now = DateTime.Now;
            string nowfileName = now.ToString("yyyyMMddHHmmss") + Assistant.GetRandomNum(6) + sExt;

            string ServerUrl = $"~/Images/upload/news/Rich/";
            var savePath = HttpContext.Current.Server.MapPath(ServerUrl);

            try
            {
                if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                }
            }
            catch (Exception ex)
            {
                Controller.IO.LogManager.Add(ex.ToString());
            }

            string path = $"~/Images/upload/news/Rich/" + nowfileName;

            uploadFile.SaveAs(HttpContext.Current.Server.MapPath(path));
            string imgurl = PubConstant.GetConnectionString("smallAppImgUrl");
            object o = new
            {
                errno = 0, // 注意：值是数字，不能是字符串
                data = new
                {
                    url = imgurl + "Images/upload/news/Rich/" + nowfileName, // 图片 src ，必须
                    alt = "yyy", // 图片描述文字，非必须
                    href = "zzz" // 图片的链接，非必须
                }
            };

         
            return StringToJson.ObjectToJson(o);// "{\"errno\":0,data:{\"url\":\"http://localhost:58036/Images/upload/product/Rich/" + nowfileName+"\"}}";

        }

        public string Base64Upload()
        {
            string base64txt = request["base64img"];
            string ext = "png";
            //处理文件头
            if (string.IsNullOrEmpty(base64txt))
                return null;

            int i = base64txt.IndexOf("image") + 6;
            int j = base64txt.IndexOf("base64");

            if (i > -1 && j - i - 1 > 0)
            {
                ext = base64txt.Substring(i, j - i - 1);
            }
            base64txt = base64txt.Substring(base64txt.IndexOf(',') + 1);

            Random rnd = new Random();
            string nowfileName = DateTime.Now.ToString("yyyyMMddHHmmss") + rnd.Next(10000, 99999) + "." + ext;

            string filetype = PageValidate.InputText(request["Type"], 50);
            string id = PageValidate.InputText(request["id"], 50);

            string path = @"/Images/upload/news/";
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

            path = path + nowfileName;
            //过滤特殊字符
            string dummyData = base64txt.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }
           
            StringToFile(dummyData, HttpContext.Current.Server.MapPath(path));

            return XhdResult.Success(nowfileName).ToString();
        }

        /// <summary>  
        /// 把经过base64编码的字符串保存为文件  
        /// </summary>  
        /// <param name="base64String">经base64加码后的字符串 </param>  
        /// <param name="fileName">保存文件的路径和文件名 </param>  
        /// <returns>保存文件是否成功 </returns>  
        private static bool StringToFile(string base64String, string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            if (!string.IsNullOrEmpty(base64String) && File.Exists(fileName))
            {
                bw.Write(Convert.FromBase64String(base64String));
            }
            bw.Close();
            fs.Close();
            return true;
        }



    }
}